//
//  WDCarViewController.m
//  OpenSesame
//
//  Created by zhangjiaming on 17/5/10.
//  Copyright © 2017年 OpenSesame. All rights reserved.
//

#import "WDCarViewController.h"
#import "WDCarListCell.h"
#import "WDCar.h"
#import  "UIImageView+WebCache.h"
#import "WDKeyListController.h"
#define CARList @"http://47.92.139.238/copying/index/carList"
@interface WDCarViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong )UITableView *tableView;
@property (nonatomic,strong)NSMutableArray * indexDataSource;
@property (nonatomic,strong)NSMutableArray * allDataSource;
@property (nonatomic,strong)NSArray *dataSource;
@end

@implementation WDCarViewController


#pragma  mark 懒加载

-(NSMutableArray *)indexDataSource{
    if (!_indexDataSource) {
        _indexDataSource =[NSMutableArray arrayWithCapacity:100];
    }
    return _indexDataSource;
}
-(NSMutableArray *)allDataSource{
    if (!_allDataSource) {
        _allDataSource =[NSMutableArray arrayWithCapacity:100];
    }
    return _allDataSource;
}
-(NSArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSArray array];
    }
    return _dataSource;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"汽车钥匙";
    self.tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"WDCarListCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"carlist"];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.tableView.sectionIndexColor = [UIColor grayColor];
    [self getData];
    
}

-(void)getData{
        NSUserDefaults *defult =[NSUserDefaults standardUserDefaults];
    
        WDLog(@"%@",[defult objectForKey:@"token"]);
    

      [JMHttpTool post:CARList param:@{@"token":[defult objectForKey:@"token"]} success:^(id responseObject) {
          NSDictionary *dict =[NSDictionary dictionaryWithDictionary:responseObject];
          _dataSource = [WDCar mj_objectArrayWithKeyValuesArray:dict[@"data"]];
          WDLog(@"aaaaa%@",_dataSource);
          [self allDataRanger];
          [self.tableView reloadData];
      } frail:^(NSError *error) {
          WDLog(@"%@",error);
      }];
}

- (void)allDataRanger {
    // 通讯录排序，分组
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    //得出collation索引的数量，这里是27个（26个字母和1个#）
    NSInteger sectionTitlesCount = [[collation sectionTitles] count];
    NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
    //初始化27个空数组加入newSectionsArray
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [newSectionsArray addObject:array];
    }
    //将每个人按name分到某个section下
    for (WDCar *model in _dataSource) {
        //获取name属性的值所在的位置，比如"林丹"，首字母是L，在A~Z中排第11（第一位是0），sectionNumber就为11
        NSInteger sectionNumber = [collation sectionForObject:model collationStringSelector:@selector(name)];
        //把name为“林丹”的p加入newSectionsArray中的第11个数组中去
        NSMutableArray *sectionNames = newSectionsArray[sectionNumber];
        [sectionNames addObject:model];
    }
    //对每个section中的数组按照name属性排序
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *personArrayForSection = newSectionsArray[index];
        NSArray *sortedPersonArrayForSection = [collation sortedArrayFromArray:personArrayForSection collationStringSelector:@selector(name)];
        newSectionsArray[index] = sortedPersonArrayForSection;
    }
    //将排序好的通讯录名单存到数据库里面
    //    [messageDbManger saveUserToDataBase:_allDataSource];
    
    NSMutableArray *temp = [NSMutableArray new];
    _indexDataSource = [NSMutableArray new];
    [newSectionsArray enumerateObjectsUsingBlock:^(NSArray *arr, NSUInteger idx, BOOL *stop) {
        if (arr.count == 0) {
            [temp addObject:arr];
        } else {
            [_indexDataSource addObject:[collation sectionTitles][idx]];
        }
    }];
    _allDataSource =[[NSMutableArray alloc]init];
    [newSectionsArray removeObjectsInArray:temp];
    [_allDataSource removeAllObjects];
    [_allDataSource addObjectsFromArray:newSectionsArray];
    WDLog(@"%@",_allDataSource);
}
#pragma mark - Table view data source



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return _allDataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [_allDataSource[section] count];
}

//返回头视图内容
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
   
            UILabel *label = [[UILabel alloc] init];
            label.backgroundColor = [UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1];
            label.textAlignment = NSTextAlignmentLeft;
            label.text = [NSString stringWithFormat:@"    %@",_indexDataSource[section]];
            return label;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 20;
}

//右侧索引列表
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    
        return _indexDataSource;
}
//索引点击事件
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    
    [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    return index;
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WDCarListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"carlist" forIndexPath:indexPath];
     WDCar * model = _allDataSource[indexPath.section][indexPath.row];
    WDLog(@"%@",model);
    NSString *imgStr =[NSString stringWithFormat:@"%@%@",@"http://47.92.139.238/",model.pic];
    [cell.carImageView sd_setImageWithURL:[NSURL URLWithString:imgStr] placeholderImage:[UIImage imageNamed:@"baoma"]];
    cell.carLabel.text = model.name ;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WDCar * model = _allDataSource[indexPath.section][indexPath.row];
    WDKeyListController *keyList =[[WDKeyListController alloc]init];
    keyList.name = model.name;
    keyList.carID = model.cId;
    [self.navigationController pushViewController:keyList animated:YES];

}


@end
